import os
import time
import datetime
import sys

import etcd3

os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"]="python"

MAX_DB_SIZE = os.getenv("MAX_DB_SIZE")
CHECK_PERIOD = os.getenv("CHECK_PERIOD")

# 证书文件路径 
ca_cert = '/path/to/ca-cert.pem' 
client_cert = '/path/to/client-cert.pem' 
client_key = '/path/to/client-key.pem'

def verify_data(num):
    # 500MB
    def_value = 524288000 
    try:
        num_value = int(num)
        # 取值范围1K~2G(最大DB空间为2G), 默认设置为500M
        if 1024 <= num_value <= 2147483648:
            return num_value
        else:
            return def_value
    except Exception as exc:
        print("get max dbsize catch an exception, use the default value. {}", exc)
        return def_value


def verify_period(num):
    def_value = 720
    try:
        num_value = int(num)
        # 取值范围1-1440, 默认设置为720
        if 1 <= num_value <= 1440:
            return num_value
        else:
            return def_value
    except Exception as exc:
        print("get check period catch an exception, use the default value. {}", exc)
        return def_value


def compact_and_defrag():
    # 连接到 etcd 服务
    etcd = etcd3.client( host='127.0.0.1', port=2379, ca_cert=ca_cert, cert_cert=client_cert, cert_key=client_key )

    # 获取当前 etcd 的修订版本号
    status = etcd.status()
    revision = status['dbSize']  # 或者使用 status.header.revision
    db_size = status.dbSize  # 当前数据库大小

    if db_size < verify_data(MAX_DB_SIZE) :
        print("DB size({db_size}) is less than the threshold, no need to perform compaction and defragmentation.")
        return
    
    # 执行压缩操作
    print(f"Compacting etcd at revision {revision}...")
    etcd.compact(revision)
    print("Compaction completed.")

    # 执行碎片整理
    print("Defragmenting etcd...")
    etcd.defragment()
    print("Defragmentation completed.")


def scheduled_task():
    first_time = datetime.datetime.now()
    first_hour = first_time.hour
    flag = True
    check_period = verify_period(CHECK_PERIOD)
    remaining_times = check_period
    while True:
        remaining_times -= 1
        now = datetime.datetime.now()
        print("now datetime is: %s", now)
        if now.hour == first_hour:
            if flag and now.minute > 55:
                # backup_data()
                flag = False
            # 默认每5分钟检测一次
            if remaining_times <= 0:
                compact_and_defrag()
                remaining_times = check_period
        else:
            flag = True
            first_hour = now.hour
        time.sleep(60)

if __name__ == "__main__":
    scheduled_task()
